<template>
    <div class="login-container">
        <van-form ref="loginFormRef"
            :show-error="false" :show-error-message="false" validate-first
            @submit="onSubmit" @failed="onFailed"
            >
            <van-field
                v-model="user.userphone"
                type="tel"
                name="userphone"
                placeholder="手机号"
                maxlength="11"
                :rules="formRule.userphone"
            >
                <van-icon slot="left-icon" class-prefix="iconfont icon" name="shouji"></van-icon>
            </van-field>
            <van-field
                v-model="user.password"
                type="number"
                name="password"
                placeholder="验证码"
                maxlength="6"
                :rules="formRule.password"

            >
                <van-icon slot="left-icon" class="iconfont" class-prefix="icon" name="yanzhengma"></van-icon>
                <template #button>
                    <van-count-down v-if="showCountDown" :time="1000 * 60" format="ss s" @finish="showCountDown = false"/>
                    <van-button v-else size="mini" round type="primary" :disabled="isSendCode" @click.prevent="getCode">发送验证码</van-button>
                </template>
            </van-field>
            <div class="login">
                <van-button round block type="info" native-type="submit">登入</van-button>
            </div>
        </van-form>
    </div>
</template>
<script>
import { mapActions } from 'vuex';
import * as Api from 'api/common';

export default {
    data () {
        return {
            user: {
                userphone: '',
                password: ''
            },
            isSendCode: false,
            showCountDown: false,
            formRule: {
                userphone: [
                    { required: true, trigger: 'onBlur', message: '请填写手机号' },
                    { pattern: /^((13[0-9])|(14[5-9])|(15([0-3]|[5-9]))|(16[6-7])|(17[1-8])|(18[0-9])|(19[1|3])|(19[5|6])|(19[8|9]))\d{8}$/, trigger: 'onBlur', message: '手机号格式有误' }
                ],
                password: [
                    { required: true, trigger: 'onBlur', message: '请填写验证码' },
                    { pattern: /^\d{6}$/, trigger: 'onBlur', message: '请输入完整的验证码' }
                ]
            }
        };
    },
    methods: {
        ...mapActions(['updateUser', 'defaultCache', 'emptyCache']),
        onFailed (error) {
            if (error.errors[0]) {
                this.$toast({
                    message: error.errors[0].message,
                    position: 'top'
                });
            }
        },
        async onSubmit () {
            this.emptyCache();
            try {
                const data = {
                    mobile: this.user.userphone,
                    code: this.user.password
                };
                const res = await Api.reqDev('/v1_0/authorizations', 'post', { data });
                this.$toast.success('登入成功');
                this.updateUser(res.data);
                this.defaultCache();
                this.$router.push(this.$route.query.redicter || '/');
            } catch (err) {
                console.log(err);
            }
        },
        async getCode () {
            try {
                this.isSendCode = true;
                await this.$refs.loginFormRef.validate('userphone');
                const res = await Api.reqDev(`/v1_0/sms/codes/${this.user.userphone}`);
                if (res.message === 'OK') {
                    this.showCountDown = true;
                }
            } catch (err) {
                let message = '';
                if (err && err.response && err.response.status === 429) message = '发送太频繁了，请稍后再试'; // 接口请求太频繁
                else if (err.name === 'userphone') message = err.message; // 表单验证不通过
                else message = '发送失败，请稍后再试'; // 未知错误
                this.$toast({
                    message: message,
                    position: 'top'
                });
            }
            this.isSendCode = false;
        }
    }
};
</script>
<style lang="less" scoped>
.login-container {
    .van-cell {
        align-items: center;
        .van-button--mini {
            background-color: #ccc;
            border: none;
            padding: 0 10px;
        }
    }
    .login {
        margin: 26px 16px;
    }
}
</style>
